// pages/productDetail/productDetail.js
const app = getApp();
import myUtils from '../../utils/util.js';
import httpsUtils from '../../utils/https.js';
import commonUtils from '../../utils/common.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    circular: true,
    detailList: [],
    detailLenght: 0,
    dataShop: {},
    dataShopImg: [],
    paramaslist: [],
    datas: {},
    timeStr: '',
    commentList: [],
    isCollection: 2,//默认1表示收藏，2表示不收藏
    levelType: 1,//默认1表示星星，2表示钻石，3表示皇冠
    levelArray: [1],//默认1

    goodsType: 1, //默认1表示正常订单 3表示抢购订单
    isToday: 1, //当商品为抢购订单时，1表示今日，2表示明日
    cheapPrice: 0.00, //优惠价格
    rushRate: 0,//购买比率
    tradePrice: 0.00,//正常价格

    isBuy: 0,//默认0表示不能抢购，1表示能抢购
    goodsId:'',
    shareType:0 //跳转0首页，1表示尾货，2表示商圈，3表示商家
  },
  /**
   * 拨打电话
   */
  call: function (e){
    if (myUtils.isMobile(this.data.dataShop.phone)) {
      wx.makePhoneCall({
        phoneNumber: this.data.dataShop.phone,
        success: function () {
        },
        fail: function () {
          wx.showToast({
            title: '拨打失败',
            icon: "none"
          })
        }
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '请下载服装基地联系店家',
        showCancel: false
      })
    }
  },
  /**
   * 去店铺
   */
  gotoShop:function(e){
    var pages = getCurrentPages();
    if (pages.length >= 2){
      var info = pages[pages.length - 2].route;
      if (info == 'pages/shopInformation/shopInformation') {
        wx.navigateBack({
          delta: 1
        })
      } else {
        wx.navigateTo({
          url: "/pages/shopInformation/shopInformation?shopid=" + e.currentTarget.dataset.shopid,
        })
      }
    }else{
      wx.navigateTo({
        url: "/pages/shopInformation/shopInformation?shopid=" + e.currentTarget.dataset.shopid,
      })
    }
    
  },
  /**
   * 聊天
   */
  toChat:function(){
    wx.showModal({
      title: '提示',
      content: '需要聊天功能，请下载服装基地APP后使用',
      showCancel: false
    })
  },
  /**
 * 跳转首页
 */
  toindex: function () {
    var that = this;
    if (that.data.shareType == 1){
      var pages = getCurrentPages();
      if (pages.length >= 2) {
        wx.navigateBack({
          delta: 1
        })
      } else {
        wx.redirectTo({
          url: '../leftoverStock/leftoverStock',
          success: function () {
          },
        })
      }
    } else if (that.data.shareType == 2) {
      var pages = getCurrentPages();
      if (pages.length >= 2) {
        wx.navigateBack({
          delta: 1
        })
      } else {
        wx.redirectTo({
          url: '../businessCircleDetail/businessCircleDetail?id=' + that.data.datas.shopinfo.tradeAreaId,
          success: function () {
          },
        })
      }
    } else if (that.data.shareType == 3) {
      var pages = getCurrentPages();
      if (pages.length >= 2) {
        wx.navigateBack({
          delta: 1
        })
      } else {
        wx.redirectTo({
          url: '../shopInformation/shopInformation?shopid=' + that.data.datas.shopinfo.id,
          success: function () {
          },
        })
      }
    }else{
      var pages = getCurrentPages();
      if (pages.length >= 2) {
        wx.navigateBack({
          delta: 1
        })
      } else {
        wx.switchTab({
          url: '../index/index',
        })
      } 
    }
  },
  noTips: function () {
    wx.showModal({
      title: '提示',
      content: '非常抱歉！该店铺已暂停营业',
      showCancel: false
    })
  },
  /**
   * 查看说明
   */
  seeHelp: function (e) {
    this.showModal();
  },
  /**
   * 查看所有评价
   */
  seeComment: function (e) {
    var that = this;
    var commentList = []
    commentList = that.data.commentList;
    if (commentList.length > 0) {
      wx.navigateTo({
        url: '../comment/comment?goodsId=' + that.data.datas.goods.id + '&shopId=' + that.data.datas.shopinfo.id,
      })
    } else {
      wx.showToast({
        title: '暂无评论',
        icon: 'none'
      })
    }
  },
  /**
   * 添加足迹
   */
  addFoot: function (id) {
    httpsUtils.postData({
      _url: app.globalData._url + '/myFoot/add',
      data: { goodsId: id },
    }, function (json) {
    })
  },
  /**
   * 是否收藏商品
   */
  isCollection: function (id) {
    var that = this;
    httpsUtils.getData({
      _url: app.globalData._url + '/goods/isCollection?id=' + id,
      data: '',
    }, function (json) {
      if (json.data && json.success) {
        that.setData({
          isCollection: json.data.status,
        })
      }
    })
  },
  /**
   * 收藏商品
   */
  updateCollection: function (e) {
    var that = this;
    var goodsId = that.data.datas.goods.id;
    wx.setStorageSync("nowGoodsId", goodsId)
    httpsUtils.getData({
      _url: app.globalData._url + '/myCollection/addOrCancelMyCollection?goodsId=' + goodsId,
      data: '',
    }, function (json) {
      if (json.data && json.success) {
        if (json.data.status == 1) {
          wx.showToast({
            title: '收藏成功',
            icon: 'none'
          })
        } else {
          wx.showToast({
            title: '取消收藏成功',
            icon: 'none'
          })
        }
        that.setData({
          isCollection: json.data.status,
        })
      }
      if (json.success == false && json.code == 'OVERTIME') {
        wx.navigateTo({
          url: '../wxLogin/wxLogin?type=3&isTab=false',
        })
      }
    })
  },
  /**
   * 时间转换
   */
  timeFormat: function (goodTime) {
    var that = this;
    var nowTime = Date.parse(new Date());
    var subTime = (nowTime - goodTime) / 1000;
    var timeStr = '';
    if (subTime < 60) {
      timeStr = '刚刚';
    } else if (parseInt(subTime / 60) < 60) {
      timeStr = parseInt((subTime / 60)) + '分钟前';
    } else if (parseInt(subTime / (60 * 60)) < 24) {
      timeStr = parseInt(subTime / (60 * 60)) + '小时前';
    } else if (parseInt(subTime / (60 * 60 * 24)) < 30) {
      timeStr = parseInt(subTime / (60 * 60 * 24)) + '天前';
    } else if (parseInt(subTime / (60 * 60 * 24 * 30)) < 12) {
      timeStr = parseInt(subTime / (60 * 60 * 24 * 30)) + '月前';
    } else {
      timeStr = parseInt(subTime / (60 * 60 * 24 * 30 * 12)) + '年前';
    }
    that.setData({
      timeStr: timeStr
    })
  },
  /**
   * 等级转换
   */
  shopGrade: function (creditLevel) {
    var that = this;
    var levelType = parseInt(creditLevel / 5);
    var levelTimes = parseInt(creditLevel % 5);
    var levelArray = [];
    for (var i = 0; i < levelTimes; i++) {
      levelArray.push(levelType);
    }
    that.setData({
      levelType: levelType,
      levelArray: levelArray
    })
  },
  /**
   *  商品详情
   */
  goodDetail: function (id) {
    wx.showToast({
      title: '加载中...',
      icon: 'loading'
    })
    var that = this;
    httpsUtils.getData({
      _url: app.globalData._url + '/goods/particulars?id=' + id,
      data: {},
    }, function (json) {
      if (json.data && json.success) {
        //console.log(json.data)
        var imgUrls = [];
        if (json.data.goods.goods_url != null) {
          imgUrls = json.data.goods.goods_url.split("***");
        }
        imgUrls.unshift(json.data.goods.cover_url);

        var shopImg = json.data.shopinfo.headImg;

        var paramaslist = []
        paramaslist.push({ name: '颜色', value: json.data.colorName })
        paramaslist.push({ name: '尺码', value: json.data.sizeName })
        if (json.data.propertyList != undefined){
          for (let obj of json.data.propertyList) {
            paramaslist.push({ name: obj.oneProperty, value: obj.twoProperty })
          }
        }
        if(json.data.goods.weight > 0){
          paramaslist.push({ name: '重量', value: json.data.goods.weight+'斤' })
        }

        //格式化时间
        that.timeFormat(json.data.goods.upt_datetime);

        //设置等级
        that.shopGrade(json.data.shopinfo.creditLevel);

        that.setData({
          dataShopImg: shopImg,
          detailList: imgUrls,
          datas: json.data,
          dataShop: json.data.shopinfo,
          commentList: json.data.commentList,
          paramaslist: paramaslist
        })
      } else {

      }
      wx.hideToast();
    })
  },
  /**
   * 初始化参数
   */
  initData: function (options) {
    var that = this;
    if (options.goodsType != undefined) {
      that.setData({
        goodsType: options.goodsType,
        isToday: options.isToday,
        rushRate: options.rushRate,
        tradePrice: options.tradePrice,
        cheapPrice: options.cheapPrice,
      })
      that.initTime();
    }
    if (options.shareType != undefined) {
      that.setData({
        shareType: options.shareType
      })
    }
    
  },
  /**
   * 限时抢购距离结束时间
   */
  initTime: function () {
    var that = this;
    httpsUtils.getData({
      _url: app.globalData._url + '/rushTime/getRushTime',
      data: '',
    }, function(json) {
      that.cutdown(json)
    })
  },
  cutdown:function(json){
    var that = this;
    var new_date = new Date();
    var years = new_date.getFullYear();    // 获取完整的年份(4位,1970-????)
    var month = ("0" + (new_date.getMonth() + 1)).slice(-2);       // 获取当前月份(0-11,0代表1月)
    var days = new_date.getDate();        // 获取当前日(1-31)
    var new_date_times = new_date.getTime();        // 获取当前时间(从1970.1.1开始的毫秒数)
    var currentTimes = years + "-" + month + "-" + days;
    var end_times = currentTimes + json.data.endTime;
    var start_times = currentTimes + ' ' + json.data.startTime;
    var end_date_times = new Date(end_times).getTime();//获取毫秒值
    var start_date_times = new Date(start_times).getTime();
    var tom_start_date_times = start_date_times + 86400000; //明天开始时间
    if (json.data && json.success) {
      if (start_date_times <= new_date_times <= end_date_times) {
        var diff_time = Math.floor((end_date_times - new_date_times) / 1000);
        var hour_time = ("0" + Math.floor(diff_time / 3600 % 24)).slice(-2);
        var minute_time = ("0" + Math.floor(diff_time / 60 % 60)).slice(-2);
        var second_time = ("0" + Math.floor(diff_time % 60)).slice(-2);
        that.setData({
          isBuy: 1,
          hourTime: hour_time,
          minuteTime: minute_time,
          secondTime: second_time,
        })
      } else if (start_date_times > new_date_times) {
        var diff_time = Math.floor((start_date_times - new_date_times) / 1000);
        var hour_time = ("0" + Math.floor(diff_time / 3600 % 24)).slice(-2);
        var minute_time = ("0" + Math.floor(diff_time / 60 % 60)).slice(-2);
        var second_time = ("0" + Math.floor(diff_time % 60)).slice(-2);
        that.setData({
          isBuy: 0,
          hourTime: hour_time,
          minuteTime: minute_time,
          secondTime: second_time,
          isToday: 2
        })
      } else {
        that.setData({
          isBuy: 0,
          hourTime: "00",
          minuteTime: "00",
          secondTime: "00",
          isToday: 1
        })
      }

      var tom_diff_time = Math.floor((tom_start_date_times - new_date_times) / 1000);
      var tom_hour_time = ("0" + Math.floor(tom_diff_time / 3600 % 24)).slice(-2);
      var tom_minute_time = ("0" + Math.floor(tom_diff_time / 60 % 60)).slice(-2);
      var tom_second_time = ("0" + Math.floor(tom_diff_time % 60)).slice(-2);
      that.setData({
        tomHourTime: tom_hour_time,
        tomMinuteTime: tom_minute_time,
        tomSecondTime: tom_second_time,
        limitDeta: json.data,
      })

      setTimeout(function () {
        that.cutdown(json)
      }, 1000)
    }
  },
  
  /**
   * 预览
   */
  imgYu: function (event){
    var src = event.currentTarget.dataset.src;//获取data-src
    var imgList = event.currentTarget.dataset.list;//获取data-list
    //图片预览
     wx.previewImage({
      current: src, // 当前显示图片的http链接
       urls: imgList // 需要预览的图片http链接列表
   })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var shareType = 0;
    if (options.shareType != undefined && options.shareType != null){
      shareType = options.shareType;
    }
    that.setData({
      goodsId: options.id,
      shareType: shareType
    })
    //初始化参数
    that.initData(options);
    //商品详情
    that.goodDetail(options.id);
    //添加足迹
    that.addFoot(options.id);
    //是否收藏
    that.isCollection(options.id);
   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if (app.globalData.isFlush == true) {
      //是否收藏
      that.isCollection(that.data.datas.goods.id);
      app.globalData.isFlush = false;
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    that.setData({
      indicatorDots: true,
      autoplay: true,
      interval: 3000,
      duration: 1000,
      circular: true,
      detailList: [],
      detailLenght: 0,
      dataShop: {},
      dataShopImg: [],
      paramaslist: [],
      datas: {},
      timeStr: '',
      commentList: [],
      isCollection: 2,//默认1表示收藏，2表示不收藏
      levelType: 1,//默认1表示星星，2表示钻石，3表示皇冠
      levelArray: [1],//默认1

      isBuy: 0,//默认0表示不能抢购，1表示能抢购
    })

    //商品详情
    that.goodDetail(that.data.goodsId);
    //添加足迹
    that.addFoot(that.data.goodsId);
    //是否收藏
    that.isCollection(that.data.goodsId);

    wx.stopPullDownRefresh(); 
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (this.data.shareType == 1){
      return {
        title: '尾货特价,谁要?',
        path: '/pages/productDetail/productDetail?id=' + this.data.goodsId,
      }
    }else{
      return {
        title: this.data.datas.goods.goods_title,
        path: '/pages/productDetail/productDetail?id=' + this.data.goodsId,
      }
    }
    
  },
  getData: function (params, cb) {
    // console.log(params)
    wx.request({
      url: params._url,
      data: params.data,
      method: 'GET',
      header: {
        'content-type': 'application/json;charset=UTF-8'
      },
      success: function (res) {
        if (res.statusCode == 200) {
          typeof cb === 'function' && cb(res.data)
        }
      },
      fail: function () {
      },
      complete: function () {
      }
    })
  },
  //显示对话框
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  }
})